# ============================================================================ #
# Copyright (c) 2022 - 2025 NVIDIA Corporation & Affiliates.                   #
# All rights reserved.                                                         #
#                                                                              #
# This source code and the accompanying materials are made available under     #
# the terms of the Apache License 2.0 which accompanies this distribution.     #
# ============================================================================ #

get_filename_component(NVQIR_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
include(CMakeFindDependencyMacro)

get_filename_component(PARENT_DIRECTORY ${NVQIR_CMAKE_DIR} DIRECTORY)

find_dependency(CUDAQOperator REQUIRED HINTS "${PARENT_DIRECTORY}/cudaq")
find_dependency(CUDAQCommon REQUIRED HINTS "${PARENT_DIRECTORY}/cudaq")
find_package(fmt QUIET)
if (NOT fmt_FOUND)
  include(FetchContent)
  FetchContent_Declare(
    fmt
    GIT_REPOSITORY https://github.com/fmtlib/fmt
    GIT_TAG        @CUDAQ_FMTLIB_HASH@) 
  FetchContent_MakeAvailable(fmt)
endif()

if(NOT TARGET nvqir::nvqir)
    include("${NVQIR_CMAKE_DIR}/NVQIRTargets.cmake")
endif()

get_filename_component(PARENT_DIRECTORY ${PARENT_DIRECTORY} DIRECTORY)
set(NVQIR_SIMULATOR_PLUGIN_PATH "${PARENT_DIRECTORY}")
get_filename_component(PARENT_DIRECTORY ${PARENT_DIRECTORY} DIRECTORY)
set(NVQIR_SIMULATOR_CONFIG_PATH "${PARENT_DIRECTORY}/targets")

include("${NVQIR_CMAKE_DIR}/NVQIRTargetConfigGen.cmake")

function(nvqir_add_backend BackendName GPURequirements)
  set(LIBRARY_NAME nvqir-${BackendName})
  set(INTERFACE_POSITION_INDEPENDENT_CODE ON)

  add_library(${LIBRARY_NAME} SHARED ${ARGN})
  target_link_libraries(${LIBRARY_NAME} PRIVATE nvqir::nvqir)
  install(TARGETS ${LIBRARY_NAME} DESTINATION ${NVQIR_SIMULATOR_PLUGIN_PATH})
  nvqir_write_target_config(${BackendName} ${GPURequirements} ${CMAKE_BINARY_DIR}/${BackendName}.yml)
  install(FILES ${CMAKE_BINARY_DIR}/${BackendName}.yml DESTINATION ${NVQIR_SIMULATOR_CONFIG_PATH})
endfunction()
